from dvadmin.utils.json_response import DetailResponse
from dvadmin.utils.serializers import CustomModelSerializer
from rest_framework.response import Response
from rest_framework import status
from dvadmin.utils.viewset import CustomModelViewSet
from ops.devops.models import Deploy, Module
from ops.devops.utils.utils_jks import JksOp
from ops.devops.utils.util_config import get_config
import asyncio
import json


class DeploySerializer(CustomModelSerializer):
    """
    devops-序列化器
    """
    class Meta:
        model = Deploy
        fields = '__all__'
        read_only_fields = ["id"]


class DeployViewSet(CustomModelViewSet):
    """
    devops接口
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    exclude_field = []
    queryset = Deploy.objects.all()
    serializer_class = DeploySerializer
    extra_filter_backends = []
    permission_classes = []
    search_fields = ["name"]

    def create(self, request, *args, **kwargs):
        # 获取post提交的body数据
        data = request.data

        # 获取配置
        conf = get_config('jenkins')
        serializer = self.get_serializer(data=data)
        serializer.is_valid(raise_exception=True)

        # 从传入的参数获取env version 模块id等
        env = data.get('env')
        version = data.get('version')
        alias_name = data.get('alias_name')

        module_tmp = Module.objects.get(alias_name=alias_name)

        # 获取相关参数
        params_json = json.loads(module_tmp.params)
        jenkins_job_name = params_json.get(env).get('jks_job_name')

        params = params_json.get(env).get('jks_params')
        params['TAG_OR_BRANCH'] = version

        # 更新版本号
        module_tmp.version = version
        module_tmp.save()
        # 异步任务调用jenkins
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        res = loop.run_until_complete(JksOp.build_job(conf.get('jks_url'), conf.get('jks_user'), conf.get('jks_password'), jenkins_job_name, params))
        self.perform_create(serializer)
        return Response(res, status=status.HTTP_201_CREATED)
